package com.jt.config;
/*
全局过滤器设计及实现
 */
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class AuthGatewayFilter  implements GlobalFilter, Ordered {
    @Value("${white.prefix}")
    private String whitePerfix;//动态属性赋值
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();//1.获取对象
        String path = request.getURI().getPath();//2.获取路径
        System.out.println("path:"+path);//path:/nacos/provider/get/100
        System.out.println("perfix:"+whitePerfix);//perfix:/nacos
        String username = request.getQueryParams().getFirst("username");//3.获取参数

        if(!path.startsWith(whitePerfix)) {//1.判断路径的前缀
            //2.获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            //3.设置响应状态码,这里的值为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            //4.增添响应业务的内容
            Map<String,Object> map=new HashMap();
            map.put("message","request failure");
            map.put("status",502);
            //5.gson转换json格式
            Gson gson = new Gson();
            String jsonSt = gson.toJson(map);
            byte[] bytes = jsonSt.getBytes();
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));//{"message":"request failure","status":502}
            //问rest-api.http文件,当配置信息不匹配要求，响应给出的业务内容，


            //6.结束当前请求
            //return response.setComplete();
        }
        //4.返回响应结果
        return chain.filter(exchange);//将请求交给下一个过滤器进行处理
    }

     @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;//最高优先权；
    }
}
